<template>
    <van-popup v-model="showFlag" class="vanout">
        <div class="code-container2" v-show="imgDone"><img src="" alt="" class="log-re"/></div>
        <div class="code-container" v-show="!imgDone" ref="share">
            <!--            <p class="title">{{ systemData.name || '爱润妍' }}</p>-->

            <div class="log">
                <img :src="systemImg || systemData.pic" alt=""/>
                <div class="right">
                    <p class="p1">{{ systemData.brandname }}</p>
                    <p class="p2">{{ systemData.Advertisement }}</p>
                </div>
            </div>

            <div class="user">
                <p>{{ polyAccount.nickname || 'XXX' }}的店</p>
            </div>

            <div class="code">
                <img :src="qrcodeWechat" style="width: 155px;height:155px" v-if="interState"/>
                <qrcode :text="qrcode" :size="155" error-level="M" v-else></qrcode>
            </div>
        </div>
    </van-popup>
</template>
<script>
    import {commonMixin, sysMixin, wxMixin} from '@/common/mixin';
    import API from '@/request/api';
    import html2canvas from 'html2canvas';
    import {isIOS} from '@/common/utils';

    export default {
        mixins: [commonMixin, sysMixin, wxMixin],
        data() {
            return {
                showFlag: false,
                defaultBrand: '',
                defaultSystem: '',
                defaultUid: '',
                avatarBase64: this.polyAccount.avatar,
                imgDone: false,
                systemImg: '',
                qrcodeWechat: '',
                interState: false // 是否小程序环境,默认web环境
            };
        },
        props: {
            polyAccount: {
                type: Object,
                isRequired: true,
                default: () => {
                    return {};
                }
            }
        },
        created() {
            // this._getdefaultBrand()
            if (window.__wxjs_environment === 'miniprogram') {
                //    判断是否先程序环境
                this.interState = true;
            }
        },
        mounted() {
            this.prepareWxShare(this.qrcode, {
                name: '邀约关注',
                dec: '',
                pic: this.systemImg,
            });
        },
        computed: {
            qrcode() {
                //聚合二维码
                let protocol = window.protocol ? window.protocol : 'http';
                return `${protocol}://${document.domain}/welcome?aid=${this.polyAccount.id}`;
            }
        },
        watch: {
            polyAccount() {
                this.request.post(API.qrcode, {
                    scene: {
                        aid: this.polyAccount.id
                    }
                }).then(res => {
                    console.log(res, 'ressss');
                    this.qrcodeWechat = res.base64;
                    // wx.miniProgram.postMessage({
                    //     data: {
                    //         system: this.system,
                    //         referid: this.uid,
                    //         title: '产品名字',
                    //         type: 'online-detail'
                    //     }
                    // });
                });
            }
        },
        beforeRouteEnter(to, from, next) {
            // 修复iOS版微信h5 History兼容性问题
            if (isIOS() && to.path !== location.pathname) {
                location.assign(to.fullPath); // 此处不可使用location.replace
            } else {
                next();
            }
        },
        methods: {
            //获取申请列表
            _getdefaultBrand() {
                return this.request
                    .get(API.getDefaultBrand, {})
                    .then((res) => {
                        this.defaultBrand = res.brand;
                        this.defaultSystem = res.system;
                        this.defaultUid = res.uid;
                    })
                    .catch((err) => {
                        this.$toast.fail(err);
                    });
            },
            show() {
                this.showFlag = true;
                if (!this.imgDone) {
                    this.conversion();
                }
            },
            hide() {
                this.showFlag = false;
            },
            _getBase64(url) {
                if (!url) {
                    return '';
                }
                return this.request.get(API.picbase64, {url: url});
            },
            formatBase64Src(base64) {
                return `data:image/png;base64,${base64}`;
            },
            domToImg() {
                let shareNode = this.$refs.share;

                // const options = {useCORS: true};
                var options = {
                    scrollY: 0, // 纵向偏移量 写死0 可以避免滚动造成偶尔偏移的现象
                    useCORS: true // 【重要】开启跨域配置
                };
                setTimeout(() => {
                    html2canvas(shareNode, options).then((canvas) => {
                        let img = document.querySelector('.log-re');
                        img.src = canvas.toDataURL();
                        this.imgDone = true;
                    });
                }, 20);

            },
            // domToImg() {
            //     let shareNode = document.querySelector('.code-container');
            //     console.log(shareNode.offsetWidth, shareNode.offsetHeight);
            //     var width = shareNode.offsetWidth; //获取dom 宽度
            //     var height = shareNode.offsetHeight; //获取dom 高度
            //     var canvas = document.createElement('canvas'); //创建一个canvas节点
            //     var scale = window.devicePixelRatio || 5; //定义任意放大倍数 支持小数
            //     canvas.width = width * scale; //定义canvas 宽度 * 缩放
            //     canvas.height = height * scale; //定义canvas高度 *缩放
            //     canvas.style.width = width + 'px';
            //     canvas.style.height = height + 'px';
            //     canvas.getContext('2d').scale(scale, scale);
            //     canvas.getContext('2d').translate(0, 0);
            //     var opts = {
            //         scale: scale, // 添加的scale 参数
            //         canvas: canvas, //自定义 canvas
            //         logging: true, //日志开关，便于查看html2canvas的内部执行流程
            //         width: width, //dom 原始宽度
            //         height: height,
            //         dpi: window.devicePixelRatio,
            //         useCORS: true, // 【重要】开启跨域配置
            //         windowWidth: shareNode.scrollWidth,
            //         windowHeight: shareNode.scrollHeight
            //     };
            //     setTimeout(() => {
            //         html2canvas(shareNode, opts).then((canvas) => {
            //             var ctx = canvas.getContext('2d');
            //             // 【重要】关闭抗锯齿
            //             ctx.mozImageSmoothingEnabled = false;
            //             ctx.webkitImageSmoothingEnabled = false;
            //             ctx.msImageSmoothingEnabled = false;
            //             ctx.imageSmoothingEnabled = false;
            //
            //             let img = document.querySelector('.log-re');
            //             img.src = canvas.toDataURL();
            //             console.log(canvas.toDataURL().substr(10, 20));
            //             this.imgDone = true;
            //             // this.downloadFile(`分享${this.product.name}.png`, canvas.toDataURL());
            //         });
            //     },100)
            //
            // },
            async conversion() {
                //获取base64编码 解决移动端跨域问题
                try {
                    let imgResult = await this._getBase64(this.systemData.pic);
                    this.systemImg = this.formatBase64Src(imgResult.content);
                } catch (e) {
                    console.log(e);
                }
                setTimeout(() => {
                    this.domToImg();
                }, 20);
            }
        }
    };
</script>
<style lang="stylus" scoped>
    @import '~assets/main.styl'

    .van-popup {
        overflow-y: hidden !important;
        background-color: rgba(0, 0, 0, 0) !important;
        transition: none 0s; // 很关键 去掉popup的过渡动画 因为这可能会影响html2canvas的渲染结果 引起偏移等现象
    }

    .vanout {
        overflow hidden
    }

    * {
        box-sizing border-box
    }

    .code-container2 {
        width 300px

        .log-re {
            width 300px
        }
    }

    .code-container {
        width 300px
        background grayF
        text-align center
        padding 50px 0
        border-radius 5px

        .log {
            margin 0 50px
            flex-x()

            img {
                flex-shrink 0
                width 60px
                height 60px
                border-radius 10px
            }

            .right {
                height 60px
                padding 5px 0 5px 10px
                flex-y(space-between, flex-start)

                .p1 {
                    word-vw(word14, gray3)
                    line-height 19px
                }

                .p2 {
                    word-vw(word12, gray3)
                    line-height 16px
                    text-align left
                }
            }
        }

        .code {
            text-align center
            margin 0 70px
            width 155px
            height 155px
        }

        .user {
            text-align center
            margin 50px 0 10px 0
        }
    }
</style>

